package cn.powertime.evaluation.app.controller;

import cn.powertime.evaluation.Constants;
import cn.powertime.evaluation.config.AlUtils;
import cn.powertime.evaluation.entity.CpLionUser;
import cn.powertime.evaluation.entity.SysUser;
import cn.powertime.evaluation.enums.HttpStatus;
import cn.powertime.evaluation.facade.SysUserFacade;
import cn.powertime.evaluation.service.CpLionUserService;
import cn.powertime.evaluation.service.SysUserService;
import cn.powertime.evaluation.shiro.ShiroUtils;
import cn.powertime.evaluation.util.PasswordHelper;
import cn.powertime.evaluation.vo.*;
import cn.powertime.evaluation.web.controller.BaseController;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

/**
 * @author liqi
 * @Description: pc端用户管理模块
 * @date 2019/4/18
 */
@RestController
@RequestMapping(value = "/app/user")
@Api(value = "/app/user", tags = "用户接口", produces = MediaType.ALL_VALUE)
public class AppUserController extends BaseController {

    @Autowired
    private SysUserFacade sysUserFacade;

    @Autowired
    private CpLionUserService cpLionUserService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation(value = "验证账号唯一性", notes = "")
    @PostMapping("/checkUserNameOnly")
    public Object checkOnly(String account, Long id) {
        boolean b = sysUserFacade.checkUserNameOnly(account, id);
        if (b) {
            return error(HttpStatus.CHECK_FAIL, null, "账号已存在");
        }
        return success("账号可用");
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "")
    public Object add(@Validated @RequestBody ReqUserAddVo addVo) {
        String password = addVo.getPassword();
        if (!StringUtils.equals(password, addVo.getRepeatPassword())) {
            return error("两次输入密码不一致");
        }
        addVo.setRepeatPassword("");
        boolean b = sysUserFacade.add(addVo);
        if (b) {
            return success("用户注册成功");
        }
        return error("用户注册失败");
    }

    @PostMapping("/edit")
    @ApiOperation(value = "修改用户信息", notes = "")
    public Object edit(@Validated @RequestBody ReqSysUserEditVo editVo) {
        boolean b = sysUserFacade.edit(editVo);
        if (b) {
            return success("修改用户成功");
        }
        return error("修改用户失败");
    }

    @PostMapping("/editLion")
    @ApiOperation(value = "修改用户等保信息", notes = "")
    public  Object cpLionUser(@Validated @RequestBody CpLionUser cpLionUser){
        cpLionUser.setId(ShiroUtils.getUserInfo().getId());
        cpLionUser.setUserId(ShiroUtils.getUserInfo().getId());
        cpLionUser.setUpdateTime(LocalDateTime.now());
        boolean b=cpLionUserService.ownUpdateById(cpLionUser);
        if (b) {
            return success("修改用户成功");
        }
        return error("修改用户失败");
    }

    @ApiOperation(value = "修改密码", notes = "")
    @PostMapping(value = "/updatePwd")
    public Object updatePwd(@Validated @RequestBody  ReqSysUserUpdatePwdVo vo) {
        String  sendSms = stringRedisTemplate.opsForValue().get(vo.getAccount() + "-sendSms");
        if(sendSms==null){
            return error("手机号与获取验证码的号码不一致或没有获取验证码!");
        }
        JSONObject  jsonObject =  JSONObject.parseObject(sendSms);
        String c =  jsonObject.getString("code");
        String time=jsonObject.getString("time");
        Long times=  Long.parseLong(time);
        if(System.currentTimeMillis()-times>1000 * 60*5){
            return error("验证码已过期!");
        }
        if(!(vo.getSmsCode().equals(c))){
            return error("验证码不正确!");
        }
        if (!StringUtils.equals(vo.getNewPassword(), vo.getRepPassword())) {
            return error("两次输入密码不一致");
        }
        vo.setRepPassword("");
        boolean b = sysUserFacade.updatePwdApp(vo);
        if (b) {
            return success("成功");
        }
        return error("失败");
    }

    @ApiOperation(value = "用户信息", notes = "")
    @GetMapping(value = "/userLionInfo")
    public Object userInfoLion() {
       // RespSysUserLionVo  sysUser= sysUserService.myUserLionById(ShiroUtils.getUserInfo().getId());
        RespSysUserLionVo  sysUser= sysUserService.myUserLionById(ShiroUtils.getUserInfo().getId());
        sysUser.setPassword("");
        return success(sysUser);
    }

//    @ApiOperation(value = "重置密码", notes = "")
//    @PostMapping(value = "/resetPwd")
//    public Object resetPwd(@Validated @RequestBody ReqSysUserResetPwdReqVo vo) {
//        if (!StringUtils.equals(vo.getNewPassword(), vo.getRepPassword())) {
//            throw new BusinessException("两次输入密码不一致");
//        }
//        vo.setRepPassword("");
//        boolean b = sysUserFacade.resetPwd(vo);
//        if (b) {
//            return success("密码重置成功");
//        }
//        return error("密码重置失败");
//    }

    @ApiOperation(value = "用户详情", notes = "")
    @GetMapping(value = "/details/{id}")
    public Object details(@PathVariable("id") @NotNull(message = "字典类型ID不能为空") Long id) {
        SysUser sysUser = sysUserFacade.details(id);
        sysUser.setPassword("");
        return success(sysUser);
    }

    @ApiOperation(value = "用户信息", notes = "")
    @GetMapping(value = "/userInfo")
    public Object userInfo() {
        SysUser sysUser = sysUserFacade.details(ShiroUtils.getUserInfo().getId());
        sysUser.setPassword("");
        return success(sysUser);
    }

    @PostMapping("/update/account")
    @ApiOperation(value = "修改帐号信息",notes ="")
    public Object updateUserInfo(@Validated @RequestBody ReqSysUserUpdateReqVo editVo){
        boolean b = sysUserFacade.accountUpdate(editVo);
        if(b){
            return success("修改账号成功");
        }
        return error("修改账号失败");
    }

    @PostMapping("/remove")
    public Object delteteUserInfo(){
        SysUser sysUser = new SysUser();
        sysUser.setStatus( Constants.STATUS_DEL);
        sysUser.setId(ShiroUtils.getUserInfo().getId());
        boolean b= sysUserService.updateByIdS(sysUser);

        if(b){
             return success("成功");
        }
        return error("失败");
    }

    @PostMapping("/updateD")
    public Object updatePassword(@Validated @RequestBody  ReqSysUserUpdatePwdVo vo){
        vo.setRepPassword("");
        List<SysUser> userList = sysUserFacade.selectByAccount(vo.getAccount());
        SysUser user = userList.get(0);
        String pwd = PasswordHelper.builder().build().encrypt( vo.getAccount() ,vo.getOldPassword(), user.getPwdSalt());
        // 验证密码
        if(!StringUtils.equalsIgnoreCase(pwd,user.getPassword())){
            return error("密码错误！");
        }
        boolean b = sysUserFacade.updatePwdApp(vo);
        if (b) {
            return success("成功");
        }
        return error("失败");
    }

    @ApiOperation(value = "用户信息等保", notes = "")
    @GetMapping(value = "/userInfoApp")
    public  Object userInfoAPP(){
        RespSysUserLionVo vo= sysUserService.myUserLionById(ShiroUtils.getUserInfo().getId());
        return success(vo);
    }


    @PostMapping("/sendSms")
    @ApiOperation(value = "获取手机验证码", notes = "")
    public  Object sendSms(@Validated @RequestBody AppSendSmsVo vo){
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("account", vo.getAccount());
        wrapper.ne("status", Constants.STATUS_DEL);
        int i= sysUserService.count(wrapper);
        if(i<0){
            return  error("账号输入错误!");
        }
        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
        AlUtils alUtils = new AlUtils();
        boolean b=alUtils.send(vo.getAccount() ,verifyCode);
        if(!b){
            return error("验证码发送失败!");
        }else {
            stringRedisTemplate.delete(vo.getAccount() + "-sendSms");//根据key删除缓存
            Long sendTime= System.currentTimeMillis();
            AppCodeTimeVo vo1= new AppCodeTimeVo();
            vo1.setCode(verifyCode);
            vo1.setTime(sendTime.toString());
            stringRedisTemplate.opsForValue().set(vo.getAccount() + "-sendSms", JSONObject.toJSONString(vo1));

        }
        return  success();
    }
}
